﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using GMAC.ReportingSystem.Business.Entities;
using System.Data;
using GMAC.ReportingSystem.Business;
using GMAC.ReportingSystem.Business.Components;

namespace GMAC.ReportingSystem.Paginas
{
    public partial class InsuranceCompanies : System.Web.UI.Page
    {
        #region Page Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated || Session["User"] == null)
            {
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                return;
            }
            
            if (IsPostBack) return;
            
            Initialize();
            
            ValidateSecurity();
            
        }

        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Button Events

        protected void btnNew_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var bc               = new InsuranceCompanyComponent();
                var insuranceCompany = ReadInsuranceCompany();

                insuranceCompany.Id  = bc.Create(insuranceCompany);
                
                var audit = new FrameworkManapro.Audit.Audit<InsuranceCompany>
                {
                    EntityKey = insuranceCompany.Id.ToString(),
                    EventDate = DateTime.Now,
                    EventType = FrameworkManapro.Audit.AuditEvent.Insert,
                    NewObject = insuranceCompany,
                    UserId = ((User)Session["User"]).UserID
                };

                var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<InsuranceCompany>(audit);
                
                auditDAC.InsertAudit();
                
                wucMessage.ShowMessage(UserControls.MessageType.Success, "The Insurance Company was successfully saved.", null);
                
                popupExtenderMessage.Show();
                
                this.PagingControl.TotalRecords = Search();
                
                Search();

                ClearFields();
            }
            catch (Exception ex)
            {
                var message = (ex.Message == "DuplicateNameException") ? "There is already a Insurance Company with this name." : "The Historic Re-Purchase could not be saved";
                
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "New Historic RePurchase", "btnNew_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, message, null);
                popupExtenderMessage.Show();
            }
        }

        //----------------------------------------------------------------

        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            btnNew.Visible  = true;
            
            var bc = new  InsuranceCompanyComponent();

            try
            {
                var insuranceCompany = ReadInsuranceCompany();

                if (this.hfID.Value.Trim() != string.Empty)
                {
                    insuranceCompany.Id = int.Parse(hfID.Value);

                    var oldInsuranceCompany = bc.GetDetails(insuranceCompany.Id);

                    bc.Edit(insuranceCompany);

                    var audit = new FrameworkManapro.Audit.Audit<InsuranceCompany>
                    {
                        EntityKey = insuranceCompany.Id.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Update,
                        OldObject = oldInsuranceCompany,
                        NewObject = insuranceCompany,
                        UserId = ((User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<InsuranceCompany>(audit);

                    auditDAC.InsertAudit();

                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The Insurance Company was successfully saved.", null);
                    popupExtenderMessage.Show();

                    this.PagingControl.TotalRecords = Search();

                    Search();

                    ClearFields();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "New Insurance Company", "btnNew_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The Insurance Company could not be saved", null);
                popupExtenderMessage.Show();
            }
        }

        //----------------------------------------------------------------

        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            btnNew.Visible  = true;

            ClearFields();
        }

        //----------------------------------------------------------------

        protected void btnModify_Click(object sender, ImageClickEventArgs e)
        {
            if (this.grvInsuranceCompanies != null)
            {
                if (grvInsuranceCompanies.SelectedDataKey != null)
                {
                    try
                    {
                        var insuranceCompanyId   = (int)this.grvInsuranceCompanies.SelectedDataKey.Value;
                        var bc                   = new InsuranceCompanyComponent();
                        var insuranceCompany     = bc.GetDetails(insuranceCompanyId);

                        hfID.Value               = insuranceCompanyId.ToString();
                        txtID.Text               = insuranceCompany.Id.ToString();
                        txtName.Text             = insuranceCompany.Name.ToString();
                        optOptions.SelectedValue = (insuranceCompany.Status == GeneralEnumTypes.Status.Active).ToString();
                        
                        btnSave.Visible          = true;
                        btnNew.Visible           = false;
                    }
                    catch (Exception ex)
                    {
                        FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Modify Insurance Company", "btnModify_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                        wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred changing the Insurance Company.", ex.ToString());
                        popupExtenderMessage.Show();
                    }
                }
                else
                {
                    wucMessage.ShowMessage(UserControls.MessageType.Information, "A Insurance Company must be selected.", null);
                    popupExtenderMessage.Show();
                }
            }
        }

        //----------------------------------------------------------------

        protected void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            if (grvInsuranceCompanies.SelectedDataKey != null)
            {
                popupExtenderConfirm.Show();
            }
            else
            {
                wucMessage.ShowMessage(UserControls.MessageType.Information, "A Insurance Company must be selected.", null);
                popupExtenderMessage.Show();
            }
        }

        //----------------------------------------------------------------

        protected void btnConfirm_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var bc = new InsuranceCompanyComponent();

                if (grvInsuranceCompanies.SelectedDataKey != null)
                {
                    var insuranceCompanyId  = (int)this.grvInsuranceCompanies.SelectedDataKey.Value;
                    var insuranceCompany    = new InsuranceCompany { Id = insuranceCompanyId };
                    var oldInsuranceCompany = bc.GetDetails(insuranceCompanyId);

                    bc.Delete(oldInsuranceCompany);

                    var audit = new FrameworkManapro.Audit.Audit<InsuranceCompany>
                    {
                        EntityKey = insuranceCompany.Id.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Delete,
                        OldObject = oldInsuranceCompany,
                        UserId    = ((User)Session["User"]).UserID
                    };

                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<InsuranceCompany>(audit);
                    
                    auditDAC.InsertAudit();
                    
                    this.PagingControl.TotalRecords = Search();
                    
                    Search();
                    
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The Insurance Company was successfully deleted.", null);
                    popupExtenderMessage.Show();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Delete Insurance Company", "btnConfirm_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The Insurance Company couldn't be deleted.", ex.ToString());
                popupExtenderMessage.Show();
            }
        }
        
        //----------------------------------------------------------------

        protected void imgBuscarReg_Click(object sender, ImageClickEventArgs e)
        {
            this.PagingControl.TotalRecords = Search();
            
            Search();
            
            if (this.PagingControl.TotalRecords == 0)
            {
                PagingControl.Visible = false;
            }
            else
            {
                PagingControl.Visible = true;
            }

            ClearFields();
        }
        
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Other Events

        protected void grvInsuranceCompanies_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["OnClick"] = ClientScript.GetPostBackEventReference(grvInsuranceCompanies, "Select$" + e.Row.RowIndex);

                if ((GeneralEnumTypes.Status)Enum.Parse(typeof(GeneralEnumTypes.Status), ((HiddenField)e.Row.FindControl("hfStatus")).Value) == GeneralEnumTypes.Status.Active)
                {
                    e.Row.Cells[2].Text = "Active";
                }
                else
                {
                    e.Row.Cells[2].Text = "Inactive";
                }
            }
        }

        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Private Methods

        private void ClearFields()
        {
            txtID.Text               = string.Empty;
            txtName.Text             = string.Empty;
            txtIDSearch.Text         = string.Empty;
            txtNameSeach.Text        = string.Empty;
            optOptions.SelectedValue = "True";
            hfID.Value               = string.Empty;

        }

        //---------------------------------------------------------------------
        
        private void Initialize()
        {
            try
            {             
                optOptions.SelectedValue = "True";
                btnSave.Visible          = false;
                btnNew.Visible           = true;

                wucMessageConfirm.ShowMessage(UserControls.MessageType.Information, "Are you sure you want to delete the selected Insurance Company?", null);
                
                this.PagingControl.TotalRecords = Search();
				
                Search();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Initialize page", "Initialize", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error occurred initializing the page.", ex.ToString());
                popupExtenderMessage.Show();
            }
        }

        //---------------------------------------------------------------------

        private void ValidateSecurity()
        {
            var beEntities = ((User)Session["User"]).Role.Security.GetEntitySecurity("InsuranceCompanies");

            if (beEntities == null)
            {
                return;
            }
            
            if (!beEntities.CanRead)
            {
                grvInsuranceCompanies.Visible = false;
                btnModify.Visible             = false;
                btnDelete.Visible             = false;
                pnlSearch.Visible             = false;
            }
            if (!beEntities.CanWrite)
            {
                btnSave.Visible = false;
            }
            if (!beEntities.CanInsert)
            {
                btnNew.Visible    = false;
                btnCancel.Visible = false;
                pnlEdit.Visible   = false;
            }
            if (!beEntities.CanDelete)
            {
                btnDelete.Visible = false;
            }
        }
        
        //---------------------------------------------------------------------
        
        private int Search()
        {
            try
            {
                txtNameSeach.Text = txtNameSeach.Text.Trim();
                txtIDSearch.Text  = txtIDSearch.Text.Trim();

                var  bc = new GMAC.ReportingSystem.Business.Components.InsuranceCompanyComponent();

                int? id = (!string.IsNullOrEmpty(txtIDSearch.Text)) ? (int?)Convert.ToInt32(txtIDSearch.Text) : null;

                string name   = txtNameSeach.Text;

                FrameworkManapro.WebUI.PagingDetails paging = new FrameworkManapro.WebUI.PagingDetails();
                
                paging.PageNumber                           = this.PagingControl.PageNumber;
                paging.PageSize                             = this.PagingControl.PageSize;
                paging.SortBy                               = this.PagingControl.SortExpression;
                paging.SortDirection                        = this.PagingControl.SortDirection;

                InsuranceCompanyCollection InsuranceCompanies = bc.Search(id, name, paging);

                grvInsuranceCompanies.DataSource = InsuranceCompanies;
                grvInsuranceCompanies.DataBind();

                return InsuranceCompanies.TotalResults;
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Search Insurance Companies", "int Search", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred during the search.", ex.ToString());
                popupExtenderMessage.Show();
                return 0;
            }
        }

        //---------------------------------------------------------------------

        private InsuranceCompany ReadInsuranceCompany()
        {
            txtName.Text = txtName.Text.Trim();

            var insuranceCompany = new InsuranceCompany
            {
                Name   = txtName.Text,
                Status = (GeneralEnumTypes.Status)(bool.Parse(optOptions.SelectedValue) ? 1 : 0)
            };

            if (!string.IsNullOrEmpty(txtID.Text))
            {
                insuranceCompany.Id = Convert.ToInt32(txtID.Text);
            }

            return insuranceCompany;
        }

        //---------------------------------------------------------------------

        protected void pagingControl_PageChanged(object sender, EventArgs e)
        {
             Search();
        }
        
        #endregion

        ///////////////////////////////////////////////////////////////////////

        #region Tests

        private DataTable GenerateDataTablePrueba()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(string));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Status", typeof(string));
            DataRow rowdt;
            rowdt = dt.NewRow();
            rowdt[0] = "1";
            rowdt[1] = "Seguros Canarias";
            rowdt[2] = "true";
            dt.Rows.Add(rowdt);
            
            return dt;

        }

        #endregion

    }
}
